package net.wisos.opn.search;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.core.CoreContainer;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.context.ServletContextAware;

public class SearchServerFactory implements FactoryBean<SolrServer>,
		DisposableBean, ServletContextAware, InitializingBean {
	private static Logger logger = Logger.getLogger(SearchServerFactory.class);
	private EmbeddedSolrServer solrServer;
	private ServletContext servletContext;
	private String solrHome;

	@Override
	public void destroy() throws Exception {
		if (solrServer != null) {
			solrServer.shutdown();
		}
	}

	@Override
	public SolrServer getObject() throws Exception {
		return solrServer;
	}

	@Override
	public Class<SolrServer> getObjectType() {
		return SolrServer.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (solrHome == null) {
			solrHome = servletContext.getRealPath("/") + "solr-home";
		}
		createSearchServer();
	}

	private void createSearchServer() {
		System.setProperty("solr.solr.home", solrHome);
		try {
			CoreContainer.Initializer initializer = new CoreContainer.Initializer();
			CoreContainer coreContainer = initializer.initialize();
			this.solrServer = new EmbeddedSolrServer(coreContainer, "");
		} catch (Exception e) {
			logger.error("Create EmbeddedSolrServer error.", e);
		}
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	/**
	 * @return the solrHome
	 */
	public String getSolrHome() {
		return solrHome;
	}

	/**
	 * @param solrHome
	 *            the solrHome to set
	 */
	public void setSolrHome(String solrHome) {
		this.solrHome = solrHome;
	}

}